/**
 * 所属节点：智能货位列表
 * 创建人：zm
 * 创建时间：2024年8月19日
 * 最后修改人：zm
 */
cb.define(process.env.__DOMAINKEY__, ["common/common_VM.Extend.js"], function (common) {
  let GDGY01_dxq_locationList_VM_Extend = {
    doAction: function (name, viewModel) {
      if (this[name]) this[name](viewModel);
    },
    init: function (viewModel) {
      // 加载全局配置
      //let resConfig = cb.rest.invokeFunction("754087d70f0b45b3b6b60ebb0f899ea1", {},function(err, res) {},viewModel, {async:false});
      const qianzhui = "/gdgy/pc/isv2";
      viewModel.on("customInit", function (data) {
        // console.log("========[智能货位列表]");
        // 智能货位--页面初始化
        let tenantID = viewModel.getAppContext().tenant.tenantId;
        let userInfo = viewModel.getAppContext().user;
        let sysId = userInfo.sysId;
        let searchFlag = false;
        let flagDebug = false;
        viewModel.flagBack = false;
        viewModel.selectedHuowei = [];
        viewModel.getParams().autoAddRow = false;
        //获取查询区模型
        var gridModel = viewModel.get("dxq_location_2053979702180708428");
        gridModel._set_data("forbiddenDblClick", true);
        gridModel.setState("showRowNo", true);
        gridModel.setState("showCheckBox", false);
        //页面DOM加载完成
        viewModel.on("afterMount", function () {
          viewModel.getCache("FilterViewModel").getParams().filterRows = 3;

          // 获取查询区模型
          const filtervm = viewModel.getCache("FilterViewModel");

          //查询区模型DOM初始化后
          filtervm.on("afterInit", function () {
            //console.log("[customInit-afterInit]");
          });
        });

        viewModel.on("beforeSearch", function (args) {
          if (searchFlag) {
            args.isExtend = true;
            let commonVOs = args.params.condition.commonVOs;
            // console.log("beforeSearch", args);
            // console.log(commonVOs);
            for (var i = 0; i < commonVOs.length; i++) {
              if (commonVOs[i].itemName === "parent") {
                commonVOs.splice(i, 1);
                //return false;
              }
            }
            // console.log(commonVOs);
            searchFlag = false;
          }
        });

        //afterSetDataSource界面加载完成后，对数据进行修改afterStateRuleRunGridActionStates
        gridModel.on("afterSetDataSource", () => {
          //获取列表所有数据
          const rows = gridModel.getRows();
          //从缓存区获取按钮
          const actions = gridModel.getCache("actions");
          if (!actions) return;
          const actionsStates = [];
          rows.forEach((data) => {
            const level = data.level;
            const actionState = {};
            actions.forEach((action) => {
              //设置按钮可用不可用
              if (level === 0) {
                actionState[action.cItemName] = { visible: false };
                //同步按钮-20240730
                //if(data.warehouseName == "" && action.cItemName == "button3pi"){
                //  actionState[action.cItemName] = {visible: true };
                //}
              } else if (action.cItemName == "btnDelete") {
                actionState[action.cItemName] = { visible: true };
              } else if (action.cItemName == "btnEdit") {
                actionState[action.cItemName] = { visible: true };
              } else {
                actionState[action.cItemName] = { visible: false };
              }
              actionState["btnCopy"] = { visible: false };
            });
            actionsStates.push(actionState);
          });
          gridModel.setActionsState(actionsStates);
          // console.log("level", actionsStates)
          // 按钮更新不生效 延迟更新状态
          setTimeout(function () {
            gridModel.setActionsState(actionsStates);
          }, 100);
        });

        // function getTreeData(orgid) {
        //   // console.log('[getTreeData]', orgid)
        //   //创建同步接口请求对象
        //   const reqParams = {
        //     orgid: orgid,
        //     userId: userInfo.userId,
        //     tenant_id: tenantID,
        //   };
        //   let treeResult = cb.rest.invokeFunction(
        //     "GDGY01.Location.GetLoactionTree",
        //     { reqParams: reqParams },
        //     function (err, res) {},
        //     viewModel,
        //     { async: false }
        //   );
        //   debugger;
        //   let data = JSON.parse(treeResult.result.strResponse);
        //   console.log("aaaaaaa00", data);
        //   return data;
        // }

        /**
         * 张明迁移
         */
        viewModel.on("beforeBatchdelete", function (params) {
          // console.log("beforeBatchdelete");
          debugger;
          let domainKey = params.params.domainKey;
          let deldata = JSON.parse(params.data.data);
          // console.log(deldata);
          let locationId = deldata[0].id;

          let url = qianzhui + "/location/CheckLocationDel?tenant_id=" + tenantID + "&locationId=" + locationId;
          const proxy = viewModel.setProxy({
            CheckLocationDel: {
              url: url,
              method: "GET",
              options: {
                mask: false,
              },
            },
          });
          const resultdel = proxy.CheckLocationDelSync({});
          if (resultdel.status === "1" || resultdel.status === 1) {
            if (resultdel.data === false) {
              cb.utils.alert("该位置存在数据关联,不能删除！", "error");
              return false;
            } else {
              //console.log("success");
            }
          } else {
            cb.utils.alert("数据加载异常,请刷新后重试!", "error");
            return false;
          }

          // //传参
          // const reqParams = {
          //   locationId: locationId,
          //   tenant_id: tenantID,
          // };
          // //检查货位是否可以删除接口
          // let checkResult = cb.rest.invokeFunction(
          //   "GDGY01.Location.CheckLocationDel",
          //   { reqParams: reqParams },
          //   function (err, res) {},
          //   viewModel,
          //   { async: false }
          // );

          // let result = JSON.parse(checkResult.result.strResponse);
          // if (result.status === "1" || result.status === 1) {
          //   if (result.data === false) {
          //     cb.utils.alert("该位置存在数据关联,不能删除！", "error");
          //     return false;
          //   } else {
          //     console.log("success");
          //   }
          // } else {
          //   cb.utils.alert("数据加载异常,请刷新后重试!", "error");
          //   return false;
          // }
        });
        // 删除后操作
        viewModel.on("afterBatchdelete", function (params) {
          // //{err:null,res:Object}
          // // console.log("afterBatchdelete");
          // if (params.err == null && params.res != null) {
          //   let parentId = params.res.parent;
          //   //检查货位是否可以删除接口
          //   let checkResult = cb.rest.invokeFunction(
          //     "GDGY01.Location.CheckLocationEnd",
          //     { id: parentId },
          //     function (err, res) {},
          //     viewModel,
          //     { async: false }
          //   );
          //   // console.log(JSON.stringify(checkResult));s
          // }
          /**
           * 张明迁移
           */
          if (params.err == null && params.res != null) {
            let parentId = params.res.parent;
            const url = qianzhui + "/location/CheckLocationEnd?id=" + parentId + "&tenant_id=" + tenantID;
            const proxy = viewModel.setProxy({
              CheckLocationEnd: {
                url: url,
                method: "GET",
              },
            });
            proxy.CheckLocationEnd({}, function (err, res) {
              if (err) {
                cb.utils.alert(err.message);
              } else {
                //console.log("AAAAAAAA", res);
              }
            });
          }
        });

        //搜索表格数据之前，可以修改params参数
        gridModel.on("beforeLoad", function (params) {
          //一般主要修改默认查询的过滤条件
          /*
          to do someing...
        */
        });
      });

      // 重写编辑按钮带过去的内容
      viewModel.get("btnEdit") &&
        viewModel.get("btnEdit").on("click", function (data) {
          // 按钮--单击
          let GridModel1 = viewModel.get(data.name);
          let currentRow = GridModel1.getRow(data.index);
          viewModel.selectedHuowei = currentRow;
        });

      //同步按钮--单击同步货位上的仓库信息--暂时不用,使用时修改“按钮ID”
      // viewModel.get("button3pi") &&
      //   viewModel.get("button3pi").on("click", function (data) {
      //     // 同步--单击 WarehouseEntityAutoNextById?detailId=
      //     let GridModel1 = viewModel.get(data.name);
      //     let currentRow = GridModel1.getRow(data.index);
      //     // console.log(currentRow)
      //     const reqParams = {};
      //     let urlAPI = "/autodata/WarehouseEntityAutoNextById?detailId=" + currentRow.id; //传参可能有问题，应传入当前货位的仓库ID
      //     let rest = cb.rest.invokeFunction(
      //       "GDGY01.BaseConfig.baseData",
      //       { reqAPI: urlAPI, reqParams: reqParams },
      //       function (err, res) {},
      //       viewModel,
      //       { async: false }
      //     );
      //     let result = rest.result;
      //     // console.log(result);
      //     if (result.status != 1) {
      //       cb.utils.alert(result.message);
      //       return false;
      //     } else {
      //       cb.utils.alert(result.message);
      //       viewModel.execute("refresh");
      //     }
      //   });
    },
  };
  try {
    module.exports = GDGY01_dxq_locationList_VM_Extend;
  } catch (error) {}
  return GDGY01_dxq_locationList_VM_Extend;
});
